package com.dfhz.ken.zermall.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.dfhz.ken.zermall.R;
import com.dfhz.ken.zermall.UI.activity.shopins.FabuShopinActivity2;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by wu on 2015/10/23.
 */
public class TAkePhotos {

    private String mCurrentPhotoPath;

    private Activity activity;
    private Fragment fragment;
    private Context mContext;

    private Dialog dialog;

    public TAkePhotos(Activity activity) {
        this.activity = activity;
    }

    public TAkePhotos(Activity activity, Fragment fragment) {
        this.activity = activity;
        this.fragment = fragment;
    }

    public TAkePhotos(Context mContext,int i) {
        this.mContext = mContext;
        this.activity = (Activity)mContext;
    }

    /**
     * Message 拍照或选择本地照片dedialog
     *
     *
     */
    public void showlistviewdialog(final int index) {

        View view = LayoutInflater.from(activity).inflate(R.layout.dialog_select_image, null);
        TextView takephoto = (TextView) view.findViewById(R.id.tv_teke_picture);
        TextView selece = (TextView) view.findViewById(R.id.tv_select_photo);
        TextView no = (TextView) view.findViewById(R.id.tv_sendContentDialogFragment_cancel);

        final AlertDialog.Builder builder =
                new AlertDialog.Builder(activity, android.R.style.Theme_Holo_Light_Dialog);
        dialog = builder.create();

        dialog.getWindow().setBackgroundDrawableResource(R.drawable.transparent_bg);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setWindowAnimations(R.style.mystyle);
        dialog.setCanceledOnTouchOutside(true);

        takephoto.setAlpha(0.85f);
        selece.setAlpha(0.85f);
        no.setAlpha(0.85f);

        dialog.show();

//        WindowManager windowManager = context.getWindowManager();
//        Display display = windowManager.getDefaultDisplay();
//        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
//        lp.width = (int) (display.getWidth()); //设置宽度
        DisplayMetrics dm = activity.getApplicationContext().getResources().getDisplayMetrics();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width= (int)((dm.widthPixels)/1.05);

        dialog.getWindow().setAttributes(lp);
        dialog.setContentView(view);

        //拍照
        takephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cameraphoto(index);
                dialog.dismiss();
            }
        });

        //选择图片
        selece.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                localPicture(index);
                dialog.dismiss();
            }
        });
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * Message 选择照片
     */
    public void localPicture(int index) {
//        Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "selectimage.jpg"));
//
//        File file = new File(uri.getPath());
//        //如果父目录没有存在，则创建父目录
//        if (!file.getParentFile().exists())
//            file.getParentFile().mkdirs();
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        // 激活系统图库，选择一张图片
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");

        intent.putExtra("return-data", true);
        switch (index) {
//
//            case DingzhiActivity.PHOTO_REQUEST_CAMERA:
//                ((DingzhiActivity) mContext)
//                .startActivityForResult(intent, DingzhiActivity.PHOTO_REQUEST_GALLERY);
//                break;


        }

    }


    /**
     * 拍照
     */
    public void cameraphoto(int i) {
        Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.jpg"));

        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (photoFile != null) {

            //uri = Uri.fromFile(photoFile);

            galleryAddPic();
            Intent takePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            takePhoto.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            takePhoto.putExtra("noFaceDetection", true);
            takePhoto.putExtra("return-data", false);
            switch (i) {
                case FabuShopinActivity2.PHOTO_REQUEST_CAMERA5:
                    ((FabuShopinActivity2) activity).setUri(uri);
                    activity.startActivityForResult(takePhoto, FabuShopinActivity2.PHOTO_REQUEST_CAMERA5);
                    break;


            }


        }
    }


    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri, int index) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,
         * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么
         * 制做的了...吼吼
         */
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 500);
        intent.putExtra("outputY", 500);
        //设置剪切的图片保存位置
        Uri cropUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "crop.jpg"));
        //Uri cropUri = Uri.fromFile(new File( Environment.getExternalStorageDirectory().getPath() + "/zxy/image/crop.jpg"));
        //intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);

        File file = new File(cropUri.getPath());
        //如果父目录没有存在，则创建父目录
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();

        intent.putExtra("output", cropUri); // 输出的图片路径
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); // 输出的图片格式
        //因为我们为了获取清晰的图片，所以要将return-data设为false，
        //也就是不易data形式返回，不然，直接以data形式返回 能直接以data获取，但是获取的图片是缩略图，很模糊，
        intent.putExtra("return-data", false);

        switch (index) {
//            case Menu1Fragment.PHOTO_REQUEST_CUT1:
//                activity.startActivityForResult(intent, Menu1Fragment.PHOTO_REQUEST_CUT1);
//                break;

        }
    }


    /**
     * 拍照图片存储路径
     */
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();

        return image;
    }

    /**
     * 保存带相册
     */
    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mCurrentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        activity.sendBroadcast(mediaScanIntent);
    }

}
